package com.harmontronics.hanma.paas.paas.domain.app.service.tools;

import com.harmontronics.hanma.paas.paas.domain.app.service.DataSourceHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

import static org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_PROTOTYPE;

/**
 * @author ldb
 */
@Service("sqlClient")
@Scope(SCOPE_PROTOTYPE)
public class SqlClient {

    @Autowired
    private DataSourceHolder dataSourceHolder;

    private String dsKey;


    public SqlClient with(String dsKey) {
        this.dsKey = dsKey;
        return this;
    }


    public Object execute(SqlExecution sqlExecution) throws SQLException {
        Assert.notNull(dsKey,"未设置dsKey");
        DataSource dataSource = dataSourceHolder.getDataSource(dsKey);
        try(Connection connection = dataSource.getConnection()) {
            return sqlExecution.exec(connection);
        }

    }


}
